package com.xxkj.nmip.dialog;

import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.core.content.FileProvider;

import com.liulishuo.filedownloader.BaseDownloadTask;
import com.liulishuo.filedownloader.FileDownloadListener;
import com.liulishuo.filedownloader.FileDownloader;
import com.xxkj.nmip.R;

import java.io.File;

import razerdp.basepopup.BasePopupWindow;

public class UpDateDialog extends BasePopupWindow {
    private ProgressBar progressBar;
    private TextView tvBottom;

    public UpDateDialog(Context context, String url) {
        super(context);
        setContentView(R.layout.update_layout);
        setPopupGravity(Gravity.CENTER);
        initView(url);
    }



    private void initView( String url) {
         progressBar = findViewById(R.id.progressBar);
         tvBottom = findViewById(R.id.tv_bottom);
         startDownLoad(url);
    }
    private String getSavePath() {
        // 判断sd卡是否存在
        boolean sdCardExist = Environment.MEDIA_MOUNTED.equals(Environment
                .getExternalStorageState());
        if (sdCardExist) {
            File sdDir = Environment.getExternalStorageDirectory();// 获取根目录
            return sdDir.toString() + "/xxhis/nursinmanagement/update/nursinmanagement.apk";
        }
        return "";
    }
    private void startDownLoad(String url) {
        FileDownloader.setup(getContext());
        FileDownloader.getImpl().create(url)
                .setPath(getSavePath())
                .setListener(new FileDownloadListener() {
                    @Override
                    protected void pending(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void connected(BaseDownloadTask task, String etag, boolean isContinue, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void progress(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                        int progress = soFarBytes*100/totalBytes;
                        Log.e("下载中：",progress+"%");
                        progressBar.setProgress(progress);
                        String string = getContext().getResources().getString(R.string.download_str);
                        String progressStr = progress+"%";
                        tvBottom.setText(String.format(string,progressStr));
                    }

                    @Override
                    protected void blockComplete(BaseDownloadTask task) {
                    }

                    @Override
                    protected void retry(final BaseDownloadTask task, final Throwable ex, final int retryingTimes, final int soFarBytes) {
                    }

                    @Override
                    protected void completed(BaseDownloadTask task) {
                        Log.e("下载完成：","开始安装");
                        //开始安装apk
                        Intent intent = new Intent();
                        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                        intent.setAction(Intent.ACTION_VIEW);

                        // 判断是否是7.0
                        if (Build.VERSION.SDK_INT >= 24) {
                            // 适配android7.0 ，不能直接访问原路径
                            // 需要对intent 授权
                            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                            intent.setDataAndType(FileProvider.getUriForFile(getContext(), "com.xxkj.nmip", new File(getSavePath())), "application/vnd.android.package-archive");
                        } else {
                            intent.setDataAndType(Uri.fromFile(new File(getSavePath())), "application/vnd.android.package-archive");
                        }
                        getContext().startActivity(intent);
                    }

                    @Override
                    protected void paused(BaseDownloadTask task, int soFarBytes, int totalBytes) {
                    }

                    @Override
                    protected void error(BaseDownloadTask task, Throwable e) {
                    }

                    @Override
                    protected void warn(BaseDownloadTask task) {
                    }
                }).start();
    }
}
